import {createRouter, createWebHistory} from 'vue-router'
import Layout from '../layout/Layout.vue'

const routes = [

    {
        path: '/login',
        name: 'Login',
        component: () => import("@/views/Login")
    },

    {
        path: '/',
        name: 'Layout',
        component: Layout,
        redirect: "/login",
        meta: { title: '首页' },
        children: [
            {
                path: '/home',
                name: 'home',
                meta: { title: '首页' },
                component: () => import("@/views/Home"),

            },
            {
                path: '/user',
                name: 'user',
                meta: { title: '用户管理' },
                component: () => import("@/views/User"),

            },
            {
                path: '/role',
                name: 'role',
                meta: { title: '角色管理' },
                component: () => import("@/views/Role"),
            },
            {
                path: '/menu',
                name: 'menu',
                meta: { title: '菜单管理' },
                component: () => import("@/views/Menu"),
            },
            {
                path: '/test',
                name: 'test',
                meta: { title: '测试页面' },
                component: () => import("@/views/Test"),
            },
        ]
    },

]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

// 限制某些页面禁止未登录访问
let limitPagePath = ['/about']

router.beforeEach((to, from, next) => {
    if (limitPagePath.includes(to.path)) {
        // 判断sessionStorage是否保存了用户信息
        let userStr = sessionStorage.getItem("user") || "{}"
        let user = JSON.parse(userStr)
        if (!user.id) {
            // 跳转到登录页面
            next({path: "/login"})
        } else {
            next()
        }
    } else {
        next()
    }

})

//下面这段代码参考的B站，可以和上面的对比参考
//路由跳转之前
/*router.beforeEach((to,from,next)=>{
    //sessionStorage里面的值是在登录成功后塞进去的，参考Login.vue
    let isLogin = sessionStorage.getItem('isLogin');
    //1:如果是登出操作，那么直接将sessionStorage清空，并跳转到登录页面
    if(to.path=="/logout"){
        sessionStorage.clear()
        next({path:'/login'})
    }else if(isLogin==null){
        //2:如果没有获取到值，则说明还没登录，那直接让用户去登录页面
        next({path:'/login'})
    }else if(to.path=='/login'){
        //3:如果跳转的时候恰好是登录页面，并且isLogin是true,那么去首页
        next({path:'/home'})
    }
})*/

export default router
